<template>
  <div class="admin-user-profile">
    <!-- 页面头部 -->
    <div class="page-header">
      <el-page-header @back="handleBack">
        <template #content>
          <div class="header-content">
            <el-avatar
              :size="40"
              :src="userProfile?.basicInfo?.avatar"
              :icon="UserFilled"
            />
            <div class="header-info">
              <h2>
                {{
                  userProfile?.basicInfo?.nickName ||
                  userProfile?.basicInfo?.userName
                }}
              </h2>
              <span class="user-id"
                >ID: {{ userProfile?.basicInfo?.userId }}</span
              >
            </div>
          </div>
        </template>
        <template #extra>
          <el-button
            type="primary"
            :loading="recalculatingStats"
            @click="handleRecalculateStats"
          >
            <IconifyIconOffline icon="ep:refresh" />
            重新计算统计
          </el-button>
        </template>
      </el-page-header>
    </div>

    <!-- 主要内容区域 -->
    <div v-loading="loading" class="profile-content">
      <el-row :gutter="20">
        <!-- 左侧列 -->
        <el-col :span="16">
          <!-- 基本信息卡片 -->
          <el-card class="info-card" shadow="never">
            <template #header>
              <div class="card-header">
                <span>基本信息</span>
                <el-tag
                  :type="getUserStatusType(userProfile?.basicInfo?.status)"
                  size="small"
                >
                  {{ userProfile?.basicInfo?.statusName }}
                </el-tag>
              </div>
            </template>

            <el-descriptions :column="2" border>
              <el-descriptions-item label="用户名">
                {{ userProfile?.basicInfo?.userName }}
              </el-descriptions-item>
              <el-descriptions-item label="昵称">
                {{ userProfile?.basicInfo?.nickName }}
              </el-descriptions-item>
              <el-descriptions-item label="邮箱">
                <div class="email-info">
                  {{ userProfile?.basicInfo?.email }}
                  <el-tag
                    v-if="userProfile?.securityInfo?.isEmailVerified"
                    type="success"
                    size="small"
                  >
                    已验证
                  </el-tag>
                </div>
              </el-descriptions-item>
              <el-descriptions-item label="手机号">
                <div class="phone-info">
                  {{ userProfile?.basicInfo?.phonenumber }}
                  <el-tag
                    v-if="userProfile?.securityInfo?.isPhoneVerified"
                    type="success"
                    size="small"
                  >
                    已验证
                  </el-tag>
                </div>
              </el-descriptions-item>
              <el-descriptions-item label="性别">
                {{ userProfile?.basicInfo?.sexName }}
              </el-descriptions-item>
              <el-descriptions-item label="角色">
                <div class="roles">
                  <el-tag
                    v-for="role in userProfile?.basicInfo?.roleNames"
                    :key="role"
                    type="primary"
                    size="small"
                  >
                    {{ role }}
                  </el-tag>
                </div>
              </el-descriptions-item>
              <el-descriptions-item label="创建时间">
                {{ formatDateTime(userProfile?.basicInfo?.createTime) }}
              </el-descriptions-item>
              <el-descriptions-item label="更新时间">
                {{ formatDateTime(userProfile?.basicInfo?.updateTime) }}
              </el-descriptions-item>
              <el-descriptions-item label="创建者">
                {{ userProfile?.basicInfo?.createBy }}
              </el-descriptions-item>
              <el-descriptions-item label="更新者">
                {{ userProfile?.basicInfo?.updateBy }}
              </el-descriptions-item>
            </el-descriptions>
          </el-card>

          <!-- 统计数据卡片 -->
          <UserStatsCard :stats="userProfile?.stats" class="stats-card" />

          <!-- 内容分析卡片 -->
          <UserContentAnalysis
            :content-info="userProfile?.contentInfo"
            class="content-card"
          />

          <!-- 交互分析卡片 -->
          <UserInteractionAnalysis
            :interaction-info="userProfile?.interactionInfo"
            class="interaction-card"
          />
        </el-col>

        <!-- 右侧列 -->
        <el-col :span="8">
          <!-- 安全信息卡片 -->
          <UserSecurityInfo
            :security-info="userProfile?.securityInfo"
            class="security-card"
          />

          <!-- 最近活动卡片 -->
          <UserActivityTimeline
            :activities="recentActivities"
            class="activity-card"
            @refresh="loadRecentActivities"
            @load-more="loadMoreActivities"
            @view-all="handleViewAllActivities"
          />
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { UserFilled } from "@element-plus/icons-vue";
import { IconifyIconOffline } from "@/components/ReIcon";
import {
  getAdminUserProfileApi,
  recalculateUserStatsApi,
  getUserRecentActivitiesApi,
  getUserStatusType,
  type AdminUserProfile,
  type UserActivityRecord
} from "@/api/admin-user-profile";
import UserStatsCard from "./components/UserStatsCard.vue";
import UserContentAnalysis from "./components/UserContentAnalysis.vue";
import UserInteractionAnalysis from "./components/UserInteractionAnalysis.vue";
import UserSecurityInfo from "./components/UserSecurityInfo.vue";
import UserActivityTimeline from "./components/UserActivityTimeline.vue";

const route = useRoute();
const router = useRouter();

// 响应式数据
const loading = ref(false);
const recalculatingStats = ref(false);
const userProfile = ref<AdminUserProfile | null>(null);
const recentActivities = ref<UserActivityRecord[]>([]);

// 计算属性
const userId = computed(() => {
  return parseInt(route.params.id as string);
});

// 方法
const loadUserProfile = async () => {
  try {
    loading.value = true;
    const response = await getAdminUserProfileApi(userId.value);

    if (response && response.code === 200) {
      userProfile.value = response.data;
    } else {
      ElMessage.error(response?.message || "获取用户详情失败");
    }
  } catch (error) {
    console.error("加载用户详情失败:", error);
    ElMessage.error("获取用户详情失败");
  } finally {
    loading.value = false;
  }
};

const handleBack = () => {
  router.back();
};

const handleRecalculateStats = async () => {
  try {
    await ElMessageBox.confirm(
      "确定要重新计算该用户的统计数据吗？此操作可能需要一些时间。",
      "确认操作",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    recalculatingStats.value = true;
    const response = await recalculateUserStatsApi(userId.value);

    if (response && response.code === 200) {
      ElMessage.success("统计数据重新计算成功");
      // 重新加载用户详情
      await loadUserProfile();
    } else {
      ElMessage.error(response?.message || "重新计算统计数据失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("重新计算统计数据失败:", error);
      ElMessage.error("重新计算统计数据失败");
    }
  } finally {
    recalculatingStats.value = false;
  }
};

const loadRecentActivities = async () => {
  try {
    const response = await getUserRecentActivitiesApi(userId.value, 6);
    if (response && response.code === 200) {
      recentActivities.value = response.data;
    }
  } catch (error) {
    console.error("加载最近活动失败:", error);
  }
};

const loadMoreActivities = () => {
  // 加载更多活动记录
  loadRecentActivities();
};

const handleViewAllActivities = () => {
  // 跳转到活动记录管理页面
  router.push(`/system/user/activity?userId=${userId.value}`);
};

const formatDateTime = (timeStr?: string) => {
  if (!timeStr) return "";
  return new Date(timeStr).toLocaleString("zh-CN");
};

// 监听路由变化
watch(
  () => route.params.id,
  () => {
    if (userId.value) {
      loadUserProfile();
      loadRecentActivities();
    }
  },
  { immediate: true }
);

onMounted(() => {
  if (userId.value) {
    loadUserProfile();
    loadRecentActivities();
  }
});
</script>

<style lang="scss" scoped>
// 响应式设计
@media (width <= 1200px) {
  .admin-user-profile {
    .profile-content {
      :deep(.el-col) {
        flex: 0 0 100% !important;
        width: 100% !important;
        max-width: 100% !important;
      }
    }
  }
}

.admin-user-profile {
  min-height: calc(100vh - 84px);
  padding: 20px;
  background-color: #f5f7fa;

  .page-header {
    padding: 16px 24px;
    margin-bottom: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgb(0 0 0 / 5%);

    .header-content {
      display: flex;
      gap: 12px;
      align-items: center;

      .header-info {
        h2 {
          margin: 0;
          font-size: 18px;
          font-weight: 600;
          color: #1a202c;
        }

        .user-id {
          font-size: 12px;
          color: #64748b;
        }
      }
    }
  }

  .profile-content {
    .info-card,
    .stats-card,
    .content-card,
    .interaction-card,
    .security-card,
    .activity-card {
      margin-bottom: 20px;
    }

    .card-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-weight: 600;
    }

    .email-info,
    .phone-info {
      display: flex;
      gap: 8px;
      align-items: center;
    }

    .roles {
      display: flex;
      flex-wrap: wrap;
      gap: 4px;
    }
  }
}
</style>
